package cn.phecda.boot.tenant.test.database.jpa;

import cn.phecda.boot.data.jpa.support.CommonJpaService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * <p> TODO </p>
 *
 * @author : wanpinwei
 */
@Service
@RequiredArgsConstructor
public class PersonJpaJpaService implements CommonJpaService<PersonJpaJpaRepository, PersonJpaEntity, String> {
    private final PersonJpaJpaRepository personJpaRepository;

    @Async
    @Transactional
    @SneakyThrows
    public void asyncSave(String name) {
        TimeUnit.SECONDS.sleep(3);
        personJpaRepository.save(personJpaRepository.named(name));
    }

    @Transactional
    public PersonJpaEntity save(String name) {
        return personJpaRepository.save(personJpaRepository.named(name));
    }

    @Transactional
    public void update(String id, String name) {
        personJpaRepository.findById(id).ifPresent(person -> {
            person.setName(name);
            personJpaRepository.save(person);
        });
    }

    @Override
    public PersonJpaJpaRepository getBaseRepository() {
        return personJpaRepository;
    }
}
